#include <event2/event.h>
#include "ftp_task_retr.h"
#include "../util/common_util.h"

void XFtpRETR::Parse(std::string type, std::string msg) {
	LOGDEBUG("At XFtpRETR::Parse");
	int pos = msg.rfind(" ") + 1;
	std::string filename = msg.substr(pos, msg.size() - pos - 2);
	std::string path = cmdTask->rootDir + cmdTask->curDir + filename;
	LOGDEBUG("filepath:[" << path << "]");
	fp = fopen(path.c_str(), "rb");
	if (fp) {
		ConnectoPORT();
		ResCMD("150 File OK");
		bufferevent_trigger(bev, EV_WRITE, 0);
	}
	else {
		ResCMD("450 file open failed!");
	}
}

void XFtpRETR::Write(bufferevent *bev) {
	LOGDEBUG("At XFtpRETR::Write");
	if (!fp) return;
	int len = fread(buf, 1, sizeof(buf), fp);
	if (len <= 0) {
		ResCMD("226 Transfer complete");
		ClosePORT();
		return;
	}
	std::cout << buf;
	Send(buf, sizeof(buf));
}

void XFtpRETR::Event(bufferevent *bev, short events) {
	LOGDEBUG("At XFtpRETR::Event");
	if (events & (BEV_EVENT_EOF | BEV_EVENT_ERROR | BEV_EVENT_TIMEOUT)) {
		ClosePORT();
	}
	else if (events & BEV_EVENT_CONNECTED) {
		std::cout << "TXFtpRETR BEV_EVENT_CONNECTED" << std::endl;
	}
}




